package com.formen.ndk;

import java.io.*;
import java.net.*;
import java.sql.*;

import android.app.*;
import android.content.*;
import android.graphics.*;
import android.net.*;
import android.os.*;
import android.provider.*;
import android.support.v4.app.Fragment;
import android.util.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class Profile extends Fragment implements OnClickListener {
	ProgressDialog dialog;
	EditText edt1;
	Handler mHandler = new Handler();
	boolean checker = true;
	Bitmap imgBitmap = null;
	ImageButton img;
	String urlPath = "http://ce.sejong.ac.kr/~firebat/uploads/";
	private static final String TEMP_PHOTO_FILE = MainActivity.user_id + ".png";
	private static final int REQ_CODE_PICK_IMAGE = 0;
	private static final int RESULT_OK = -1;
	String upLoadServerUri = "http://ce.sejong.ac.kr/~firebat/UploadToServer.php";
	int serverResponseCode = 0;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.onefragment, container, false);
		img = (ImageButton) view.findViewById(R.id.imgBtn);
		img.setOnClickListener(this);
		Button button = (Button) view.findViewById(R.id.modify_bt1);
		button.setOnClickListener(this);
		TextView tv1 = (TextView) view.findViewById(R.id.tvName);
		edt1 = (EditText) view.findViewById(R.id.editText1);
		mHandler = new Handler();
		tv1.setText("\n" + MainActivity.user_name + "\n\n");
		edt1.setText(MainActivity.user_status);

		if (MainActivity.imgBitmap == null) {
			ImgThread img1 = new ImgThread();
			dialog = new ProgressDialog(getActivity());
			dialog.setTitle("");
			dialog.setMessage("이미지 받아오는 중....");
			dialog.show();
			img1.setDaemon(true);
			img1.start();
		} else
			img.setImageBitmap(MainActivity.imgBitmap);

		return view;
	}

	private Bitmap ProfileImage(String strImageURL) {
		Bitmap imgBitmap = null;

		try {
			URL url = new URL(strImageURL);
			URLConnection conn = url.openConnection();
			conn.connect();

			int nSize = conn.getContentLength();
			BufferedInputStream bis = new BufferedInputStream(
					conn.getInputStream(), nSize);
			imgBitmap = BitmapFactory.decodeStream(bis);
			MainActivity.imgBitmap = imgBitmap;
			bis.close();
		} catch (Exception e) {
			dialog.dismiss();
			e.printStackTrace();
		}
		return imgBitmap;

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.modify_bt1:
			SubThread sub1 = new SubThread();
			dialog = new ProgressDialog(getActivity());
			dialog.setTitle("");
			dialog.setMessage(MainActivity.user_name + "님의 Status를 "
					+ edt1.getText() + "로 수정중...");
			dialog.show();
			sub1.setDaemon(true);
			sub1.start();
			Toast.makeText(getActivity(), "변경되었습니다", Toast.LENGTH_LONG).show();
			break;
		case R.id.imgBtn:
			Intent intent = new Intent(
					Intent.ACTION_GET_CONTENT, // 또는 ACTION_PICK
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			intent.setType("image/*"); // 모든 이미지
			intent.putExtra("crop", "true"); // Crop기능 활성화
			intent.putExtra("aspectX", 3);
			intent.putExtra("aspectY", 4);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri()); // 임시파일
			// 생성
			intent.putExtra("outputFormat", // 포맷방식
					Bitmap.CompressFormat.JPEG.toString());

			startActivityForResult(intent, REQ_CODE_PICK_IMAGE);
			// REQ_CODE_PICK_IMAGE == requestCode


			break;
		}
	}
	
	/** 임시 저장 파일의 경로를 반환 */
	private Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}
	
	/** 외장메모리에 임시 이미지 파일을 생성하여 그 파일의 경로를 반환 */
	private File getTempFile() {
		if (isSDCARDMOUNTED()) {
			File f = new File(Environment.getExternalStorageDirectory()+"/E-Profile/", // 외장메모리
					// 경로
					TEMP_PHOTO_FILE);

			File sdCard = new File(Environment.getExternalStorageDirectory()+"/E-Profile/",
					TEMP_PHOTO_FILE);
			try {
				f.createNewFile(); // 외장메모리에 temp.jpg 파일 생성
			} catch (IOException e) {
			}

			return f;
		} else
			return null;
	}
	
	/** SD카드가 마운트 되어 있는지 확인 */
	private boolean isSDCARDMOUNTED() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;

		return false;
	}
	
	

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent imageData) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, imageData);
		switch (requestCode) {
		case REQ_CODE_PICK_IMAGE:
			if (resultCode == RESULT_OK) {
				if (imageData != null) {
					String filePath = Environment.getExternalStorageDirectory()
							+ "/E-Profile/" + TEMP_PHOTO_FILE;

					System.out.println("path" + filePath); // logCat으로 경로확인.

					Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
					Bitmap resizedbitmap = Bitmap.createScaledBitmap(
							selectedImage, 300, 400, true);
					// temp.jpg파일을 Bitmap으로 디코딩한다.

					img.setImageBitmap(resizedbitmap);
					MainActivity.imgBitmap = resizedbitmap;
					// temp.jpg파일을 이미지뷰에 씌운다.
				}
				UploadThread upl1 = new UploadThread();
				dialog = new ProgressDialog(getActivity());
				dialog.setTitle("");
				dialog.setMessage("Uploading...");
				dialog.show();
				upl1.setDaemon(true);
				upl1.start();
			}
			break;
		}
	}



	class UploadThread extends Thread {
		public void run() {
			String sourceFileUri = Environment.getExternalStorageDirectory()
					+ "/E-Profile/" + TEMP_PHOTO_FILE;
			
	          HttpURLConnection conn = null;
	          DataOutputStream dos = null;  
	          String lineEnd = "\r\n";
	          String twoHyphens = "--";
	          String boundary = "*****";
	          int bytesRead, bytesAvailable, bufferSize;
	          byte[] buffer;
	          int maxBufferSize = 1 * 1024 * 1024; 
	          File sourceFile = new File(sourceFileUri); 
	           
	          if (!sourceFile.isFile()) {
	               
	               dialog.dismiss(); 
	               Log.e("UploadThread", "Source File not exist :"
	                                   +sourceFileUri);
	               return;
	            
	          }
	          else
	          {
	               try { 
	                    
	                     // open a URL connection to the Servlet
	                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
	                   URL url = new URL(upLoadServerUri);
	                    
	                   // Open a HTTP  connection to  the URL
	                   conn = (HttpURLConnection) url.openConnection(); 
	                   conn.setDoInput(true); // Allow Inputs
	                   conn.setDoOutput(true); // Allow Outputs
	                   conn.setUseCaches(false); // Don't use a Cached Copy
	                   conn.setRequestMethod("POST");
	                   conn.setRequestProperty("Connection", "Keep-Alive");
	                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
	                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
	                   conn.setRequestProperty("uploaded_file", sourceFileUri); 
	                    
	                   dos = new DataOutputStream(conn.getOutputStream());
	          
	                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
	                   dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='"
	                                             + sourceFileUri + "'" + lineEnd);
	                    
	                   dos.writeBytes(lineEnd);
	          
	                   // create a buffer of  maximum size
	                   bytesAvailable = fileInputStream.available(); 
	          
	                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
	                   buffer = new byte[bufferSize];
	          
	                   // read file and write it into form...
	                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
	                      
	                   while (bytesRead > 0) {
	                        
	                     dos.write(buffer, 0, bufferSize);
	                     bytesAvailable = fileInputStream.available();
	                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
	                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
	                      
	                    }
	          
	                   // send multipart form data necesssary after file data...
	                   dos.writeBytes(lineEnd);
	                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	          
	                   // Responses from the server (code and message)
	                   serverResponseCode = conn.getResponseCode();
	                   String serverResponseMessage = conn.getResponseMessage();
	                     
	                   Log.i("uploadFile", "HTTP Response is : "
	                           + serverResponseMessage + ": " + serverResponseCode);
	                    
//	                   if(serverResponseCode == 200){
//	                        
//	                	   UploadThread(new Runnable() {
//	                            public void run() {
//	                                 
//	                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
//	                                              +" http://sce.sejong.ac.kr/~firebat/uploads/"
//	                                              + TEMP_PHOTO_FILE;
//	                                 
//	                                Toast.makeText(getActivity(), "File Upload Complete.", 
//	                                             Toast.LENGTH_SHORT).show();
//	                            }
//	                        });                
//	                   }    
	                    
	                   //close the streams //
	                   fileInputStream.close();
	                   dos.flush();
	                   dos.close();
	                     
	              } catch (MalformedURLException ex) {
	                   
	                  dialog.dismiss();  
	                  ex.printStackTrace();
	                   
//	                  runOnUiThread(new Runnable() {
//	                      public void run() {
//	                          messageText.setText("MalformedURLException Exception : check script url.");
//	                          Toast.makeText(UploadToServer.this, "MalformedURLException", 
//	                                                              Toast.LENGTH_SHORT).show();
//	                      }
//	                  });
	                   
	                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
	              } catch (Exception e) {
	                   
	                  dialog.dismiss();  
	                  e.printStackTrace();
	                   
//	                  runOnUiThread(new Runnable() {
//	                      public void run() {
//	                          messageText.setText("Got Exception : see logcat ");
//	                          Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", 
//	                                  Toast.LENGTH_SHORT).show();
//	                      }
//	                  });
	                  Log.e("Upload file to server Exception", "Exception : "
	                                                   + e.getMessage(), e);  
	              }
	              dialog.dismiss();       
	              return; 
	               
	           } // End else block 
			
		}
	}

	class ImgThread extends Thread {
		public void run() {
			imgBitmap = ProfileImage(urlPath + MainActivity.user_id + ".png");
			mHandler.post(new Runnable() {
				public void run() {
					if (dialog.isShowing()) {

						img.setImageBitmap(imgBitmap);
						dialog.dismiss();

					} else {
						Toast.makeText(getActivity(), "프로필 사진을 등록하세요",
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
	}

	class SubThread extends Thread {
		public void run() {
			try {
				Class.forName("com.mysql.jdbc.Driver");
				Connection conn = null;
				Statement stmt = null;
				String jdbcDriver = "jdbc:mysql://sce.sejong.ac.kr:3306/firebat?"
						+ "useUnicode=true&characterEncoding=utf8";
				String dbUser = "firebat";
				String dbPass = "a1852411";
				String query = "update nfc_user set status_msg = '"
						+ edt1.getText() + "' where user_id = '"
						+ MainActivity.user_id + "'";
				try {
					conn = DriverManager.getConnection(jdbcDriver, dbUser,
							dbPass);
					stmt = conn.createStatement();
					stmt.executeUpdate(query);
					
					MainActivity.user_status = edt1.getText().toString();
					
//					mHandler.post(new Runnable() {
//						public void run() {
//							if (pDialog.isShowing()) {
//								pDialog.dismiss();
//								Toast.makeText(getApplicationContext(),
//										user_name + " Welcome Bro :D",
//										Toast.LENGTH_SHORT).show();
//								Intent intent = new Intent(MainActivity.this,
//										Main1.class);
//								startActivity(intent);
//								finish();
//							} else {
//								Toast.makeText(
//										getApplicationContext(),
//										"Sry. Check ID/Pass or join E-Profile :p",
//										Toast.LENGTH_SHORT).show();
//							}
//						}
//					});
					
				} catch (SQLException e) {
					Toast.makeText(getActivity(), "실패", Toast.LENGTH_LONG)
							.show();
					dialog.dismiss();
					this.interrupt();
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					// 6.
					if (stmt != null)
						try {
							stmt.close();
						} catch (SQLException ex) {
						}
					// 7.
					if (conn != null)
						try {
							conn.close();
						} catch (SQLException ex) {
						}
					dialog.dismiss();
					this.interrupt();
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}